package com.cindata

import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class DataMigrationController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.sort = "modifiedDate"
        params.order = "desc"
        respond Account.list(params), model: [accountCount: Account.count()]
    }

    def getAllAccountList()
    {
        def sql = "select new map(o.id as id, o.parent.id as pId, o.name as name) from Account o where 1=1"
        def name = params['name']
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        sql += " order by level, name"

        def accountList = Account.executeQuery(sql).asList()
        render([status: "success", accountList: accountList] as JSON)
    }

    // 数据迁移页面搜索
    def searchAccountData()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def name = params["name"]
        def contact = params["contact"]
        def phone = params["phone"]
        def cellphone = params["cellphone"]

        String sql = "from Account as o where 1=1"
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        if (contact)
        {
            sql += " and o.contact like '%${contact}%'"
        }
        if (phone)
        {
            sql += " and o.phone like '%${phone}%'"
        }
        if (cellphone)
        {
            sql += " and o.cellphone like '%${cellphone}%'"
        }
        sql += ' order by modifiedDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Account.findAll(sql, [max: max, offset: offset])
        def list1 = Account.findAll(sql)
        def count = list1.size()

        respond list, model: [accountCount: count, params: params], view: 'index'
    }

    @Transactional
    def dataMigration()
    {
        def oldAccountId = params["oldAccountId"]
        def newAccountId = params["newAccountId"]

        def oldAccount = Account.findById(oldAccountId)
        if (!oldAccountId || !oldAccount)
        {
            render([status: "failed", errorMessage: '数据迁移失败，请稍后重试！'] as JSON)
            return
        }
        def newAccount = Account.findById(newAccountId)
        if (!newAccountId || !newAccount)
        {
            render([status: "failed", errorMessage: '数据迁移失败，请稍后重试！'] as JSON)
            return
        }

        def estateList = Estate.findAllByAccount(oldAccount)
        estateList?.each {
            it?.account = newAccount
            it?.save()
        }

        render([status: "success"] as JSON)
    }
}
